package com.ruoyi.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 高德地图逆地址解析工具类
 * 
 * @author ruoyi
 */
@Component
public class AmapUtils 
{
    private static final Logger logger = LoggerFactory.getLogger(AmapUtils.class);
    
    // 高德地图API key，从配置文件中读取
    @Value("${amap.api.key:}")
    private String amapApiKey;
    
    // 高德地图逆地址解析API URL
    private static final String REGEO_API_URL = "https://restapi.amap.com/v3/geocode/regeo";
    
    /**
     * 根据经纬度获取地址信息
     * 
     * @param longitude 经度
     * @param latitude 纬度
     * @return 地址信息Map，包含province、city、district、address等字段
     */
    public Map<String, String> getAddressFromCoordinate(String longitude, String latitude) {
        Map<String, String> result = new HashMap<>();
        
        if (StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude)) {
            logger.warn("经纬度参数为空，无法进行逆地址解析");
            return result;
        }
        
        if (StringUtils.isEmpty(amapApiKey)) {
            logger.warn("高德地图API Key未配置，无法进行逆地址解析");
            return result;
        }
        
        try {
            // 构建请求URL
            String location = longitude + "," + latitude;
            String urlString = REGEO_API_URL + "?key=" + amapApiKey + "&location=" + location + "&output=json&extensions=base";
            
            // 发送HTTP请求
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);
            
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            connection.disconnect();
            
            // 解析JSON响应
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.toString());
            
            // 检查API调用是否成功
            String status = jsonNode.get("status").asText();
            if (!"1".equals(status)) {
                logger.error("高德地图API调用失败，状态码: {}, 错误信息: {}", status, jsonNode.get("info").asText());
                return result;
            }
            
            // 解析地址信息
            JsonNode regeocode = jsonNode.get("regeocode");
            if (regeocode != null && !regeocode.isNull()) {
                JsonNode addressComponent = regeocode.get("addressComponent");
                if (addressComponent != null && !addressComponent.isNull()) {
                    // 提取省份
                    JsonNode province = addressComponent.get("province");
                    if (province != null && !province.isNull()) {
                        result.put("province", province.asText());
                    }
                    
                    // 提取城市
                    JsonNode city = addressComponent.get("city");
                    if (city != null && !city.isNull()) {
                        String cityText = city.asText();
                        // 处理直辖市情况（city字段可能为空数组）
                        if (StringUtils.isNotEmpty(cityText) && !"[]".equals(cityText)) {
                            result.put("city", cityText);
                        } else {
                            // 直辖市情况下，使用province作为city
                            result.put("city", result.get("province"));
                        }
                    }
                    
                    // 提取区县
                    JsonNode district = addressComponent.get("district");
                    if (district != null && !district.isNull()) {
                        result.put("district", district.asText());
                    }
                }
                
                // 提取详细地址
                JsonNode formattedAddress = regeocode.get("formatted_address");
                if (formattedAddress != null && !formattedAddress.isNull()) {
                    result.put("address", formattedAddress.asText());
                }
            }
            
            logger.info("逆地址解析成功，经纬度: {},{}, 地址: {}", longitude, latitude, result.get("address"));
            
        } catch (Exception e) {
            logger.error("高德地图逆地址解析异常，经纬度: {},{}", longitude, latitude, e);
        }
        
        return result;
    }
    
    /**
     * 根据经纬度获取地址信息（重载方法）
     * 
     * @param longitude 经度
     * @param latitude 纬度
     * @return 地址信息Map
     */
    public Map<String, String> getAddressFromCoordinate(Double longitude, Double latitude) {
        if (longitude == null || latitude == null) {
            return new HashMap<>();
        }
        return getAddressFromCoordinate(longitude.toString(), latitude.toString());
    }
    
    /**
     * 根据经纬度获取地址信息（重载方法）
     * 
     * @param longitude 经度
     * @param latitude 纬度
     * @return 地址信息Map
     */
    public Map<String, String> getAddressFromCoordinate(java.math.BigDecimal longitude, java.math.BigDecimal latitude) {
        if (longitude == null || latitude == null) {
            return new HashMap<>();
        }
        return getAddressFromCoordinate(longitude.toString(), latitude.toString());
    }
} 